<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\1\11 0011
 * Time: 10:03
 */
namespace app\admin\controller;
use think\Db;
use think\Log;

header("Content-type:text/html;charset=utf-8");
class Restore extends UserAuth {
    /**
     * 数据还原管理
     * @author 王柯 <wangke.email@foxmail.com>
     * @return \think\response\View
     */
    public function index(){

        return view('index');
    }

    /**
     * 数据还原信息列表
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json|\think\response\View
     */
    public function restore_list(){
        //数据备份目录
        $dir = ROOT_PATH.'public/backup';

        if(is_dir($dir)){
            $dir_name = scandir($dir);
            $dirArr = [];
            foreach($dir_name as $key => $val){
                if($val != '.' && $val != '..'){
                    $dirArr[] = $dir_name[$key];
                }
            }
        }else{
            exit('暂无备份文件！');
        }

        //最新备份日期
        $latest_time = $dir_name[array_keys($dir_name)[count(array_keys($dir_name)) -1]];

        //目录下文件(默认最新文件)
        $files = scandir(ROOT_PATH.'public/backup/'.$latest_time);
        if(!empty($files)){
            $file = [];
            foreach($files as $key => $val){
                if($val != '.' && $val != '..'){
                    $file[$key]['dir_date'] = $latest_time;
                    $file[$key]['file_name'] = iconv('GB2312','UTF-8',$val);
                    $file[$key]['table_name'] = explode('.',iconv('GB2312','UTF-8',$val))[0];
                }
            }
        }else{
            exit('文件夹为空！');
        }

        if(request()->isPost()){
            $data = $_POST;
            $direct_name = $data['dir_date'];

            $files = scandir(ROOT_PATH.'public/backup/'.$direct_name);
            $file = [];
            if(!empty($files)){
                foreach($files as $key => $val){
                    if($val != '.' && $val != '..'){
                        $file[$key]['dir_date'] = $data['dir_date'];
                        $file[$key]['file_name'] = iconv('GB2312','UTF-8',$val);
                        $file[$key]['table_name'] = explode('.',iconv('GB2312','UTF-8',$val))[0];
                    }
                }
            }else{
                return show(config('code.error'),'文件夹为空！');
            }
        }

        $this->assign([
            'count' => count($files),
            'dir_name' => $dirArr,
            'file' => $file,
        ]);

        return view('restore_list');
    }

    /**
     * 数据还原
     * @param $path string sql文件地址路径 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function start_restore(){
        if(request()->isAjax()){
            set_time_limit(0);    //设置不超时，程序一直运行。
            $data = $_POST;
            $time_start_second = time();
            $start_time = round(microtime(),2);
            $urlPath = ROOT_PATH.'public/backup/'.$data['param'];
            $sql = file_get_contents($urlPath);
            //preg_replace (正则表达式, 替换成, 字符串, 最大替换次数【默认-1，无数次】, 替换次数)
            //$str = preg_replace('/--.*/i', '', $str);
            //$str = preg_replace('/\/\*.*\*\/(\;)?/i', '', $str);

            //去除空格 创建数组
            //$str = explode("; ", $str);
            //$str = preg_replace("/\r\n/",'',$str);
            //$search = "\n";
            //$replace = "";
            //$str = str_replace($search,$replace,$str);

            $sql = str_replace("\r", "\n", $sql);
            $sql = explode(";\n", $sql);
            foreach ($sql as $k =>$item) {

                $item = trim($item);
                if(empty($item)) continue;

                preg_match('/CREATE TABLE `([^ ]*)`/', $item, $matches);


            }

            //sql数组
            $sqlArr = [];
            foreach ($sql as $v){
                $v = trim(preg_replace('/--.*/i', '', $v));
                if(empty($v)){
                    continue;
                }else{
                    $sqlArr[] = $v;
                }
            }

            try{
                foreach($sqlArr as $k => $v){
                    Db::query($v);
                }
            }catch (\Exception $e){
                Log::write($e->getMessage());
                return show(config('code.error'),'还原数据失败！');
            }

            $time_end_second = time();
            $end_time = $time_end_second - $time_start_second + round(microtime(),2);
            $second = $end_time - $start_time;
            set_time_limit(30);    //关闭超时，还原为默认值30s;
            return show(config('code.success'),"数据还原成功！耗时 $second s");
        }else{
            return show(config('code.error'),'非法请求！');
        }
    }

    /**
     * 下载sql文件
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function download_sql(){
        $data = input('param.');

        //文件路径
        $filePath = ROOT_PATH.'public/backup/'.$data['file_path'];

        //下载文件
        downloadFile($filePath);
    }

    /**
     * 删除备份文件
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function del_restore(){
        if(request()->isAjax()){
            $data = $_POST;

            //文件路径
            $path = ROOT_PATH.'public/backup/'.$data['param'];

            if(is_file($path)){
                $del = unlink($path);
                if($del){
                    return show(config('code.success'),'删除成功！');
                }else{
                    return show(config('code.error'),'删除失败！');
                }
            }else{
                return show(config('code.error'),'文件不存在！');
            }
        }else{
            return show(config('code.error'),'非法请求！');
        }
    }

    /**
     * 批量删除备份文件
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function batch_del_restore(){
        if(request()->isAjax()){
            $data = $_POST;

            if(empty($data['param'])){
                return show(config('code.error'),'请选择要删除的文件！');
            }

            $array = $data['param'];

            foreach($array as $key => $val){
                //文件路径
                $path = ROOT_PATH.'public/backup/'.$val;
                if(is_file($path)){
                    $del = unlink($path);
                    if(!$del){
                        return show(config('code.error'),'删除失败！');
                    }
                }else{
                    return show(config('code.error'),'文件不存在！');
                }
            }

            return show(config('code.success'),'批量删除成功！');
        }else{
            return show(config('code.error'),'非法请求！');
        }
    }

}
